import os

# 要排除的文件夹列表
remove_dir = ["venv", "__pycache__", ".git", "test"]
def exclude_directories(dirs, remove_dir):
    """排除指定的文件夹"""
    for dir in remove_dir:
        if dir in dirs:
            dirs.remove(dir)
    return dirs


def get_directory_structure(rootdir, remove_dir):
    """
    获取目录结构并返回一个字符串
    """
    structure = ""
    for root, dirs, files in os.walk(rootdir):
        dirs = exclude_directories(dirs, remove_dir)
        level = root.replace(rootdir, '').count(os.sep)
        indent = ' ' * 4 * (level)
        structure += '{}{}/\n'.format(indent, os.path.basename(root))
        subindent = ' ' * 4 * (level + 1)
        for f in files:
            structure += '{}{}\n'.format(subindent, f)
    return structure


def get_file_content(filepath):
    """
    获取文件内容并返回一个字符串
    如果是非文本文件或文件不存在，则返回空字符串
    """
    try:
        with open(filepath, 'r', encoding='utf-8') as file:
            return file.read()
    except (UnicodeDecodeError, FileNotFoundError):
        return ""


def save_project_structure_and_content(rootdir, output_file, remove_dir):
    """
    保存目录结构和文件内容到输出文件
    """
    with open(output_file, 'w', encoding='utf-8') as f:
        # 获取目录结构
        structure = get_directory_structure(rootdir, remove_dir)
        f.write("Directory Structure:\n")
        f.write(structure)
        f.write("\n\n")

        # 遍历所有文件并保存内容
        for root, dirs, files in os.walk(rootdir):
            dirs = exclude_directories(dirs, remove_dir)
            for file in files:
                if file.endswith('.py'):  # 只处理 .py 文件
                    filepath = os.path.join(root, file)
                    relative_path = os.path.relpath(filepath, rootdir)  # 获取相对于根目录的路径
                    f.write(f"File: {relative_path}\n")
                    content = get_file_content(filepath)
                    if content:  # 只保存文本文件的内容
                        f.write(content)
                    f.write("\n\n")


if __name__ == "__main__":
    # 当前工作目录
    current_directory = os.getcwd()
    # 输出文件
    output_file = "test/project_structure_and_content.txt"
    # 保存项目结构和内容
    save_project_structure_and_content(current_directory, output_file, remove_dir)

    print(f"Project structure and content saved to {output_file}")